package com.common.sdk.net.connect.http.interceptor;

import com.android.sohu.sdk.common.toolbox.StringUtils;
import com.common.sdk.net.connect.http.util.OkhttpCacheUtil;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by chengjiangsang116630 on 2018/1/30.
 *
 * 用于网络拦截器
 */


public class SohuCacheNetInterceptor extends ExceptionCatchedInterceptor {

    @Override
    protected Response realIntercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if (StringUtils.isNotBlank(request.header(CacheConstants.CACHE_CONTROL))) {
            String responseCacheControl = null;
            String requestCacheControl = request.header(CacheConstants.CACHE_CONTROL);
            if (CacheConstants.NO_CACHE.equals(requestCacheControl)) {
                responseCacheControl = CacheConstants.MAX_AGE + "=" + OkhttpCacheUtil.DEFAULT_EXPIRED_TIME;
            } else {
                responseCacheControl = requestCacheControl;
            }
            response = response.newBuilder()
                    .removeHeader(CacheConstants.PRAGMA)
                    .removeHeader(CacheConstants.CACHE_CONTROL)
                    //cache for cache seconds
                    .header(CacheConstants.CACHE_CONTROL, responseCacheControl)
                    .build();
        }
        return response;
    }

}
